package com.gulimall.order.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.gulimall.api.domain.MemberAddressDTO;
import com.gulimall.api.feign.MemberClient;
import com.gulimall.api.feign.WareClient;
import com.gulimall.common.core.domain.Result;
import com.gulimall.common.dto.cart.CartItemDTO;
import com.gulimall.order.domain.entity.Order;
import com.gulimall.order.mapper.OrderMapper;
import com.gulimall.order.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.order.vo.OrderConfirmVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.gulimall.common.constant.RedisConstants.CART_SKUINFO;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author 坤哥
 * @since 2025-08-25
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private MemberClient memberClient;
    @Resource
    private WareClient wareClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 订单确认
     */
    @Override
    public OrderConfirmVO orderConfirm() {
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();
        //获取用户的收货地址列表
        Result<List<MemberAddressDTO>> result = memberClient.getMemberReceiveAddress(1L);//因为没有实现登录功能所以用户信息写死
        List<MemberAddressDTO> memberAddressDTOList = result.getData();
        orderConfirmVO.setAddress(memberAddressDTOList);
        //获取购物车中的数据
        String json = stringRedisTemplate.opsForValue().get(CART_SKUINFO);
        CartItemDTO cartItemDTO = JSONObject.parseObject(json, CartItemDTO.class);
        List<CartItemDTO> cartItemDTOList = new ArrayList<>();
        cartItemDTOList.add(cartItemDTO);
        orderConfirmVO.setItems(cartItemDTOList);
        //获取积分信息
        Result<Integer> result1 = memberClient.getMemberIntegration();
        orderConfirmVO.setIntegration(result1.getData());
        //计算订单总额
        BigDecimal total = BigDecimal.ZERO;
        for (CartItemDTO itemDTO : cartItemDTOList) {
            BigDecimal decimal = itemDTO.getPrice().multiply(BigDecimal.valueOf(itemDTO.getCount()));
            total = total.add(decimal);
        }
        orderConfirmVO.setTotal(total);
        //计算应付价格
        BigDecimal reduce = total.multiply(BigDecimal.valueOf(0.8));
        orderConfirmVO.setPayPrice(reduce);
        return orderConfirmVO;
    }

    /**
     * 下单逻辑，把订单保存到数据库
     */
    @GlobalTransactional
    @Transactional
    @Override
    public Result toOrder() {
        //获取购物车中的数据
        String json = stringRedisTemplate.opsForValue().get(CART_SKUINFO);
        CartItemDTO cartItemDTO = JSONObject.parseObject(json, CartItemDTO.class);
        if (cartItemDTO == null) {
            return Result.fail();
        }
        BigDecimal total = null;
        if (cartItemDTO.getTotalPrice() != null) {
            total = cartItemDTO.getTotalPrice().multiply(BigDecimal.valueOf(cartItemDTO.getCount()));
        }
        //创建订单数据
        Order order = Order.builder()
                .memberId(1L)
                .orderSn(UUID.randomUUID().toString())
                .createTime(LocalDateTime.now())
                .totalAmount(total)
                .payAmount(total.multiply(BigDecimal.valueOf(0.8)))
                .freightAmount(BigDecimal.valueOf(9.0))
                .build();
        save(order);
        //扣减库存
        return wareClient.reduceWare(cartItemDTO.getSkuId(), cartItemDTO.getCount());
    }
}
